<!-- Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 2 (v2).
This example is in the Amazon Rekognition Developer Guide' at
https://docs.aws.amazon.com/rekognition/latest/dg/image-bytes-javascript.html.

Purpose:
estimate-age.html is part of an example that demonstrates how to use Amazon Rekognition to estimate the ages of faces in an image.
To view the full example, see https://docs.aws.amazon.com/rekognition/latest/dg/image-bytes-javascript.html.

Inputs :
- REGION
- IDENTITY_POOL_ID

-->

<!-- snippet-start:[rekognition.JavaScript.detect_faces_v2] -->
<!DOCTYPE html>
<html>
<head>
<script src="aws-cognito-sdk.min.js"></script>
    <script src="amazon-cognito-identity.min.js"></script>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.16.0.min.js"></script>
    <meta charset="UTF-8">
    <title>Rekognition</title>
    </head>

    <body>
    <H1>Age Estimator</H1>
<input type="file" name="fileToUpload" id="fileToUpload" accept="image/*">
    <p id="opResult"></p>
    </body>
    <script>

    document.getElementById("fileToUpload").addEventListener("change", function (event) {
        ProcessImage();
    }, false);

// Calls DetectFaces API and shows estimated ages of detected faces.
function DetectFaces(imageData) {
    AWS.region = "REGION"; // AWS Region.
    var rekognition = new AWS.Rekognition();
    var params = {
        Image: {
            Bytes: imageData
        },
        Attributes: [
            'ALL',
        ]
    };
    rekognition.detectFaces(params, function (err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else {
            var table = "<table><tr><th>Low</th><th>High</th></tr>";
            // show each face and build out estimated age table
            for (var i = 0; i < data.FaceDetails.length; i++) {
                table += '<tr><td>' + data.FaceDetails[i].AgeRange.Low +
                    '</td><td>' + data.FaceDetails[i].AgeRange.High + '</td></tr>';
            }
            table += "</table>";
            document.getElementById("opResult").innerHTML = table;
        }
    });
}
// Loads selected image and unencodes image bytes for Amazon Rekognition DetectFaces API.
function ProcessImage() {
    AnonLog();
    var control = document.getElementById("fileToUpload");
    var file = control.files[0];

    // Load base64 encoded image.
    var reader = new FileReader();
    reader.onload = (function (theFile) {
        return function (e) {
            var img = document.createElement('img');
            var image = null;
            img.src = e.target.result;
            var jpg = true;
            try {
                image = atob(e.target.result.split("data:image/jpeg;base64,")[1]);

            } catch (e) {
                jpg = false;
            }
            if (jpg == false) {
                try {
                    image = atob(e.target.result.split("data:image/png;base64,")[1]);
                } catch (e) {
                    alert("Not an image file Rekognition can process");
                    return;
                }
            }
            // Unencode image bytes for Rekognition DetectFaces API.
            var length = image.length;
            imageBytes = new ArrayBuffer(length);
            var ua = new Uint8Array(imageBytes);
            for (var i = 0; i < length; i++) {
                ua[i] = image.charCodeAt(i);
            }
            //Call Rekognition
            DetectFaces(imageBytes);
        };
    })(file);
    reader.readAsDataURL(file);
}
// Provides anonymous log on to AWS services.
function AnonLog() {

    // Configure the credentials provider to use your identity pool.
    AWS.config.region = 'REGION'; // Region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'IDENTITY_POOL_ID',
    });
    // Make the call to obtain credentials.
    AWS.config.credentials.get(function () {
        // Credentials will be available when this function is called.
        var accessKeyId = AWS.config.credentials.accessKeyId;
        var secretAccessKey = AWS.config.credentials.secretAccessKey;
        var sessionToken = AWS.config.credentials.sessionToken;
    });
}
</script>
</html>

<!-- snippet-end:[rekognition.JavaScript.detect_faces_v2] -->
<!--
    Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
    PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
-->
